<?php
/**
 * 
 * @authors Lin (callbackbing@163.com)
 * @date    2014-01-13 10:27:26
 * @version $Id$
 */

class SiteAction extends CommonAction {
    
    public function index(){

        /*引入限制模板显示字数*/
        Load('extend');

        $site_model = M('website');

        import("ORG.Util.Page");

        $agent_id = $_SESSION['agent']['id'];
        $pagenumber = 8;

        if($_GET['status'] == 'off'){
            $status = OFF;
        }else{
            $status = ON;            
        }        

        if($_GET['userName'] !== Null && $_GET['site'] !== Null){

            $username = $_GET['userName'];
            $site = $_GET['site'];
            $rs = M('user')->where("Username='".$username."' and ProxyId = $agent_id")->find();
            if($rs){
                $query = " and w.Domain='".$site."' and w.Username='".$username."'";
            }else{
                $this->error('您没有访问权限!');
            }
        }else{
            $query = " and 1=1";
        }

        $list = $site_model
        ->table('yst_user u,yst_website w')
        ->field('Domain,Webname,w.Username,w.Status,w.Id')
        ->where("u.ProxyId = $agent_id AND w.Userid IN (u.Id) and w.Status=$status".$query)
        ->page($_GET['p'])->limit($pagenumber)
        ->order('w.Id desc')->select();

        $totalnum = count($site_model
            ->table('yst_user u,yst_website w')
            ->where("u.ProxyId = $agent_id AND w.Userid IN (u.Id) and w.Status=$status".$query)
            ->select());

        $key_model = M('keyword');
        $k_list = $key_model->table('yst_keyword k,yst_user u')->field('count(k.Keyword) as k_num,k.Website')
        ->where("k.Username = u.Username AND u.ProxyId = $agent_id AND k.enyinqing = 'baidu'")->group('k.Website')->select();

        $arr = array();
        foreach ($k_list as $v) {
            $arr[$v['Website']] = $v['k_num'];
        }

        foreach ($list as $kb => &$vb) {
            $vb['k_num'] = $arr[$vb['Domain']];
            if(!isset($vb['k_num'])){
                $vb['k_num'] = 0;
            }
        }

        $this->assign("list", $list);
        $page = new Page($totalnum, $pagenumber);
        $page->setConfig("prev", "上一页");
        $page->setConfig("next", "下一页");
        $page->setConfig("first", "首页");
        $page->setConfig("last", "末页");
        $page->setConfig("theme", "<span class=pageinfo> <u></u>当前%nowPage%/%totalPage%页</span>  %first% %upPage%   %linkPage%  %downPage% %end%");
        $pageshow = $page->show();
        $this->assign("pageshow", $pageshow);

        $userstr=R("Agent/userlist");
        $this->assign('username',$userstr);
        $this->assign('list',$list);
        $this->display();
    }

    /*处理删除站点函数*/
    public function site_del(){

        if(IS_POST){
            $id = I('post.userId');
            $result = M('keyword')->where("Websiteid=$id")->find();

            if(!$result){
                $rs = M('website')->where("Id=$id")->delete();

                if($rs){
                    $ajax['status']="true";
                    $ajax['Msg']="删除成功";
                    echo json_encode($ajax);
                    die();
                }else{
                    $ajax['status']="false";
                    $ajax['Msg']="删除失败";
                    echo json_encode($ajax);
                    die();
                }

            }else{
                $ajax["status"] = "false";
                $ajax["Msg"] = "请先删除该站点下的关键词!";
                echo json_encode($ajax);
                die();
            }
        }else{
            $this->error('您没有访问权限!');
        }   
    }

    /*暂停站点处理函数*/
    public function site_stop(){

        if(IS_POST){
            $site_id = I('post.userId');
            $condition['Status'] = OFF;
            //暂停站点
            $rs = M('website')->where("Id=$site_id")->save($condition);

            //暂停该站点关键词
            M('keyword')->where("Websiteid=$site_id")->save($condition);

            if($rs){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '站点暂停成功!';
                echo json_encode($ajax);
                die();
            }else{
                $ajax['Msg'] = '站点暂停失败!';
                echo json_encode($ajax);
                die();
            }

        }else{
            $this->error('您没有访问权限!');
        }
    }

    /*开启站点处理函数*/
    public function site_start(){
        
        if(IS_POST){

            $site_id = I('post.userId');

            $condition['Status'] = ON;

            //开启站点
            $rs = M('website')->where("Id=$site_id")->save($condition);

            //开启该站点关键词
            M('keyword')->where("Websiteid=$site_id")->save($condition);

            if($rs){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '站点开启成功!';
                echo json_encode($ajax);
                die();
            }else{
                $ajax['Msg'] = '站点开启失败!';
                echo json_encode($ajax);
                die();
            }

        }else{
            $this->error('您没有访问权限!');
        }
    }

    /*异步根据用户名获取其下的站点*/
    public function site_list(){

        $agent_id = $_SESSION['agent']['id'];

        if(IS_POST){
            $data['Username'] = I('post.name');
            $data['ProxyId'] = $agent_id;

            $result = M('user')->where($data)->find();
            if($result){
                $site_arr = M('website')->where("Username='".$data['Username']."'")->field('Domain')->select();

                if($site_arr){
                    $this->assign('site_arr',$site_arr);                 
                }else{
                    $this->error('此用户下暂无站点!');
                }

            }else{
                $this->error('没有找到数据!');
            }
        }
    }

    public function site_info(){

        $agent_id = $_SESSION['agent']['id'];
        if(IS_GET){
            $site_id = I('get.id');
            $userid = M('website')->where("Id=$site_id")->getField("Userid");

            $result = M('user')->where("Id=$userid and ProxyId=$agent_id")->find();

            if($result){
                $site_info = M('website')->find($site_id);

                /*站点的累计消费*/
                $consmp_model = M('consumption');
                $data['website'] = $site_info['Domain'];
                $total_money = $consmp_model
                ->field("sum(money) as money")
                ->where($data)
                ->group("website")
                ->select();

                if($total_money[0]['money'] == NULL){
                    $total_money[0]['money']=0;
                }

                unset($data);

                /*站点关键词数量*/
                $key_model = M('keyword');
                $data['Website'] = $site_info['Domain'];
                $keys = $key_model->field('distinct Keyword')->where($data)->select();
                $key_arr = array();
                foreach ($keys as $v) {
                    $key_arr[].=$v['Keyword'];
                }        
                $str = implode('、',$key_arr);
                $this->keys = $str;
                $this->key_num = count($keys);
                $this->total_money = $total_money[0]['money'];
                $this->website = $site_info['Domain'];
                $this->sitename = $site_info['Webname'];
                $this->siteid = $site_info['Id'];
                $this->regdate = $site_info['Regdate'];
                $this->display();                  
            }else{
                $this->error('您没有访问权限!');
            }        
        }
    }

    public function site_info_save(){

        if(IS_POST){
            $id = I('post.siteid');
            $data['Domain'] = I('post.site');
            $data['Webname'] = I('post.sitename');
            $rs = M('website')->where("Id=$id")->save($data);
            if($rs !== False){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '资料提交成功!';
                echo json_encode($ajax);
            }else{
                $ajax['Msg'] = '资料提交失败!';
                echo json_encode($ajax);                
            }
        }
    }

    /*站点关键词*/
    public function site_keyword(){

        $agent_id = $_SESSION['agent']['id'];
        if(IS_GET){

            $siteid = I('get.id');
            $arr = M('website')->where("Id=$siteid")->field("Domain,Username")->find();
            $rs = M('user')->where("Username='".$arr[Username]."' and ProxyId=$agent_id")->find();

            if($rs){
                $key_model = M('keyword');

                import("ORG.Util.Page");
                $pagenumber = 8;

                $key_arr = $key_model
                ->field('Id,Keyword,Price,yinqing,Status')
                ->where("Websiteid = $siteid")
                ->page($_GET['p'])->limit($pagenumber)                
                ->select();

                $cost = M('consumption')
                ->field("SUM(money) as money,keyword,yinqing")
                ->where("website='".$arr[Domain]."'")
                ->group("keyword,yinqing")
                ->select();

                $list = array();

                foreach ($key_arr as $k=>$v) {

                    $list[$k]['Id']=$v['Id'];
                    $list[$k]['Price']=$v['Price'];
                    $list[$k]['Status']=$v['Status'];
                    $list[$k]['Keyword']=$v['Keyword'];
                    $list[$k]['yinqing']=$v['yinqing'];

                    foreach ($cost as $vb) {

                        if($v['Keyword']==$vb['keyword'] && $v['yinqing']==$vb['yinqing']){

                            if($vb['money'] == 0){
                                $list[$k]['money'] = 0;
                            }else{
                                $list[$k]['money'] = $vb['money'];
                            }

                        }
                    }
                }
                $totalnum = count($key_model->where("Websiteid = $siteid")->select());

                $page = new Page($totalnum, $pagenumber);
                $page->setConfig("prev", "上一页");
                $page->setConfig("next", "下一页");
                $page->setConfig("first", "首页");
                $page->setConfig("last", "末页");
                $page->setConfig("theme", "<span class=pageinfo> <u></u>当前 %nowPage%/%totalPage%页</span>  %first% %upPage%   %linkPage%  %downPage% %end%");
                $pageshow = $page->show();
                $this->assign("pageshow", $pageshow);
                $this->assign('list',$list);
                $this->display();
            }else{
                $this->error('您没有访问权限!');
            }            
        }

    }

    /*显示添加关键词*/
    public function site_keyword_add(){

        $agent_id = $_SESSION['agent']['id'];
        $id = I('get.id');
        $site_arr = M('website')->where("Id=$id")->find();
        $username = $site_arr['Username'];
        $result = M('user')->where("Username='".$username."' and ProxyId=$agent_id")->find();

        if($result){
            $this->assign('siteid',$id);
            $this->assign('name',$username);
            $this->assign('site',$site_arr['Domain']);
            $this->display();            
        }else{
            $this->error('您没有访问权限!');
        }
    }

    /*保存关键词*/
    public function site_keyword_save(){

        $agent_id = $_SESSION['agent']['id'];

        if(IS_POST){
            $siteid = I('post.siteid');
            $arr['keywords'] = I('post.keywords');
            $arr['moneys'] = I('post.moneys');
            $site = I('post.site');
            $name = I('post.name');

            $userid = M('user')->where("Username='".$name."'")->getField("Id");

            $agent_info = M('proxy')->where("id=$agent_id")->find();

            $yq_arr = M('proxyengine')->where("proxyid=$agent_id")->select();

            $i = 0;
            while ($i<count($arr['keywords'])) {

                $data['Websiteid'] = $siteid;
                $data['Keyword'] = $arr['keywords'][$i];

                $rs = M('keyword')->where($data)->find();

                if(!$rs){
                    $price = $arr['moneys'][$i];
                    $data['Userid'] = $userid;
                    $data['Username'] = $name;
                    $data['Website'] = $site;
                    $data['Addtime'] = date('Y-m-d H:i:s');
                    $data['Status'] = ON;
                    $data['PageoneRate'] = $agent_info['pageonerate'];
                    $data['PagetwoRate'] = $agent_info['pagetworate'];
                    $data['PagethreeRate'] = $agent_info['pagethreerate'];
                    $data['pagenumber'] = $agent_info['pagenumber'];

                    foreach ($yq_arr as $v) {
                        $data['enyinqing'] = $v['enyinqing'];
                        $data['yinqing'] = $v['yinqing'];
                        $data['Price'] = $price*$v['bili']/100;
                        $data['proxyid'] = $agent_id;
                        $result = M('keyword')->add($data);
                    }
                }

                $i++;
            }

            if($result){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '资料提交成功!';
                echo json_encode($ajax);
            }else{
                $ajax['Msg'] = '该站点已经存在此关键词!';
                echo json_encode($ajax);   
            }

            die();
        }

        $this->display();
    }

    /*关键词暂停*/
    public function keyword_stop(){

        if(IS_POST){
            $id = I('post.userId');

            $data['Status'] = OFF;

            $keyword = M('keyword')->where("id=$id")->getField("Keyword");

            $result = M('keyword')->where("Keyword='".$keyword."'")->save($data);

            if($result){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '关键词暂停成功!';
                echo json_encode($ajax);
                die();

            }else{
                $ajax['Msg'] = '关键词暂停失败!';
                echo json_encode($ajax);
                die();
            }

        }else{
            $this->error('您没有访问权限!');
        }
        
    }

    /*关键词开启*/
    public function keyword_start(){

        if(IS_POST){
            $id = I('post.userId');

            $data['Status'] = ON;

            $keyword = M('keyword')->where("id=$id")->getField("Keyword");

            $result = M('keyword')->where("Keyword='".$keyword."'")->save($data);

            if($result){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '关键词开启成功!';
                echo json_encode($ajax);
                die();
            }else{
                $ajax['Msg'] = '关键词开启失败!';
                echo json_encode($ajax);
                die();
            }

        }else{
            $this->error('您没有访问权限!');
        }
    }

    /*关键词删除*/
    public function keyword_del(){
        $id = I('post.userId');
        $this->del('keyword', $id);
    }

    /*显示添加站点*/
    public function site_add(){

        if($_POST){

            $site_model = D("website");
            if(!$site_model->create()){
                $ajax['Msg']= $site_model->getError();
                echo json_encode($ajax);
            }else{
                $data['Username'] = I('post.Username');
                $status = M('user')->where($data)->getField('Active');

                if($status == OFF){
                        $ajax['Msg']='该用户已暂停！';
                        echo json_encode($ajax);
                        die();                    
                }
                
                $data['Domain']= I('post.Domain');
                //添加站点时先判断是否有此站点
                $rs = M('website')->where($data)->field('Id')->find();
                
                if(!$rs){
                    $data['Webname'] = I('post.Webname');
                    $data['Userid']= I('post.user_id');
                    $data['Regdate'] = date('Y-m-d');
                    $result = $site_model->add($data);

                    if($result){
                        $ajax['status'] = 'true';
                        $ajax['Msg'] = '站点添加成功!';
                        $ajax['url'] = '/Site/index';
                        echo json_encode($ajax);
                    }else {
                        $ajax['Msg']='站点添加失败！';
                        echo json_encode($ajax);
                    }

                }else{
                    $ajax['Msg']='您已经拥有此站点！';
                    echo json_encode($ajax);
                }              
            }
            die();
        }
        $this->display();
    }

    /*根据用户名获取其公司名称*/
    public function ajax_company(){
        $user_Model = M('user');
        $data['ProxyId'] = $_SESSION['agent']['id'];
        $data['Username'] = I('post.Username');
        $company = $user_Model->where($data)->Field('Company,Id')->find();
        if($company){
            $ajax['status'] = 'success';
            $ajax['Msg'] = $company['Company'];
            $ajax['user_id'] = $company['Id'];
            echo json_encode($ajax);
        }else{
            $ajax['status'] = 'error';
            $ajax['Msg'] = '您没有此用户';
            echo json_encode($ajax);
        }
    }

    /*显示所有关键词列表*/
    public function site_keyword_all(){
        $agent_id = $_SESSION['agent']['id'];

        $status = I('get.status');

        import("ORG.Util.Page");
        $pagenumber = 8;

        if($status == 'off'){
            $sta = OFF;
        }else{
            $sta = ON;
        }

        if($_GET['userName'] !== Null && $_GET['site'] !== Null){

            $username = $_GET['userName'];
            $site = $_GET['site'];
            $rs = M('user')->where("Username='".$username."' and ProxyId = $agent_id")->find();
            if($rs){
                $query = " AND k.Website='".$site."'";
            }else{
                $this->error('您没有访问权限!');
            }

        }else{
            $query = " and 1=1";
        }

        $key_model = M();

        $key_arr = $key_model->table('yst_keyword k,yst_user u')
        ->field('k.id,k.Keyword,k.Username,k.enyinqing,k.Website,sum(k.Price) as Price,k.Status')
        ->where("k.Username in (u.Username) AND u.ProxyId = $agent_id AND k.Status = $sta".$query)
        ->group("k.Keyword")
        ->page($_GET['p'])->limit($pagenumber)
        ->order('u.Username desc')
        ->select();

        $totalnum = count($key_model->table('yst_keyword k,yst_user u')
        ->where("k.Username in (u.Username) AND u.ProxyId = $agent_id AND k.Status = $sta".$query)
        ->group("k.Keyword")
        ->select());

        $page = new Page($totalnum, $pagenumber);
        $page->setConfig("prev", "上一页");
        $page->setConfig("next", "下一页");
        $page->setConfig("first", "首页");
        $page->setConfig("last", "末页");
        $page->setConfig("theme", "<span class=pageinfo> <u></u>当前%nowPage%/%totalPage%页</span>  %first% %upPage%   %linkPage%  %downPage% %end%");
        $pageshow = $page->show();
        $this->assign("pageshow", $pageshow);
        //通过关键词
        $this->assign('key_arr',$key_arr);

        $userstr=R("Agent/userlist");
        $this->assign('username',$userstr);
        $this->display();
    }

    /*修改关键词*/
    public function site_keyword_edit(){

        $agent_id = $_SESSION['agent']['id'];
        if(IS_GET){
            $id = I('get.id');
            $username = M('keyword')->where("id=$id")->getField('Username');
            $rs = M('user')->where("Username='".$username."' and ProxyId=$agent_id")->find();
            if($rs){
                $key_info = M('keyword')->where("id=$id")->find();
                $this->assign('id',$key_info['id']);
                $this->assign('price',$key_info['Price']);
                $this->assign('keyword',$key_info['Keyword']);
                $this->assign('username',$key_info['Username']);
                $this->assign('site',$key_info['Website']);
                $this->assign('yq',$key_info['yinqing']);
                $this->display();
            }else{
                $this->error('您没有访问权限!');
            }
        }
    }

    /*处理关键词资料修改*/
    public function keyinfo_save(){
        
        if(IS_POST){
            $data['Price'] = I('post.cost');
            $id = I('post.id');
            $result = M('keyword')->where("id=$id")->save($data);

            if($result){
                $ajax['status'] = 'true';
                $ajax['Msg'] = '资料提交成功!';
                echo json_encode($ajax);
            }else{
                $ajax['Msg'] = '资料提交失败!';
                echo json_encode($ajax);                
            }
        }
    }

    /*推荐关键词列表*/
    public function site_keyword_recommend(){
        $agent_id = $_SESSION['agent']['id'];
        $tuijian_model = M();
        import("ORG.Util.Page");
        $pagenumber = 8;

        $tuijian_arr = $tuijian_model->table('yst_tuijian t,yst_user u')
        ->field('t.keyword,t.username,t.inputor,t.addtime,t.id')
        ->where("t.username in (u.Username) AND u.ProxyId = $agent_id")
        ->page($_GET['p'])->limit($pagenumber)
        ->order('t.id desc')
        ->select();

        $totalnum = count($tuijian_model->table('yst_tuijian t,yst_user u')->where("t.username in (u.Username) AND u.ProxyId = $agent_id")->select());

        $page = new Page($totalnum, $pagenumber);
        $page->setConfig("prev", "上一页");
        $page->setConfig("next", "下一页");
        $page->setConfig("first", "首页");
        $page->setConfig("last", "末页");
        $page->setConfig("theme", "<span class=pageinfo> <u></u>当前%nowPage%/%totalPage%页</span>  %first% %upPage%   %linkPage%  %downPage% %end%");
        $pageshow = $page->show();

        $this->assign("pageshow", $pageshow);
        $this->assign('tj_arr',$tuijian_arr);
        $this->display();
    }

    /*添加推荐关键词*/
    public function site_keyword_recommend_add(){

        $agent_id = $_SESSION['agent']['id'];

        if(IS_POST){

            $data['username'] = $_POST['name'];
            $rs = M('user')->where("Username=$data[username] and ProxyId=$agent_id")->find();

            if($rs){
                $str = I('post.tj_key');
                $arr = explode("\n", $str);
                $data['username'] = str_replace('"',"",$data['username']);
                foreach ($arr as $v) {
                    $data['keyword'] = $v;
                    $res = M('tuijian')->where($data)->find();

                    if($res){
                        $ajax['Msg'] = '该用户已经拥有此推荐词!';
                        echo json_encode($ajax);                        
                        die();
                    }

                    $data['inputor'] = $_SESSION['agent']['username'];
                    $data['addtime'] = date('Y-m-d H:i:s');
                    $result = M('tuijian')->add($data);
                }

                if($result){
                    $ajax['status'] = 'true';
                    $ajax['Msg'] = '资料提交成功!';
                    $ajax['url'] = "/Site/site_keyword_recommend";
                    echo json_encode($ajax);                    
                }else{
                    $ajax['Msg'] = '资料提交失败!';
                    echo json_encode($ajax);                    
                }

            }else{
                $ajax['status'] = 'error';
                $ajax['Msg'] = '不存在此用户!';
                echo json_encode($ajax);
            }

            die();
        }

        $userstr=R("Agent/userlist");
        $this->assign('username',$userstr);
        $this->display();
    }

    /*删除推荐关键词*/
    public function recommend_del(){
        
        $id = I('post.userId');
        $this->del('tuijian', $id);

    }
}